package com.qdxwx.web.controller.shopcart;

import com.qdxwx.common.constants.CacheConstants;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.data.service.account.UserAccountService;
import com.qdxwx.data.service.coupon.CouponCodeService;
import com.qdxwx.data.service.course.CourseService;
import com.qdxwx.data.service.member.MemberSaleService;
import com.qdxwx.data.service.member.MemberTypeService;
import com.qdxwx.data.service.shopcart.ShopCartService;
import com.qdxwx.models.coupon.CouponCodeDTO;
import com.qdxwx.models.coupon.CouponCodeQuery;
import com.qdxwx.models.course.Course;
import com.qdxwx.models.course.CourseDTO;
import com.qdxwx.models.shopcart.ShopCart;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ZhiYong
 */
@Controller
@RequestMapping( "/cart")
public class ShopCartController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(ShopCartController.class);

	@Autowired
	private ShopCartService shopCartService;
	@Autowired
	private CourseService courseService;
	@Autowired
	private CouponCodeService couponCodeService;
	@Autowired
	private MemberSaleService memberSaleService;
	@Autowired
	private MemberTypeService memberTypeService;
	@Autowired
	private UserAccountService userAccountService;

	/**
	 * 添加商品并跳转到购物车
	 */
	@RequestMapping({"/", "/index.html"})
	public String addShopCart(HttpServletRequest request, ModelMap mmap) {
		long userId = LoginUser.getUserId(request);
		if (userId < 1) {
			return "redirect:/auth/login.html";
		}
		String command = request.getParameter("command");
		if (command == null) {
			return VIEW_ERROR;
		}
		if ("addShopItem".equals(command)) {
			Integer goodsId = TKConvert.toInteger(request.getParameter("goodsId"));// 商品id
			Integer type = TKConvert.toInteger(request.getParameter("type"));// 类型1课程2套餐
			if (goodsId > 0 && type > 0) {
				// 登录用户添加到数据库
				// 查询课程信息
				Course course = courseService.get(goodsId);
				if (course == null || course.getIsAvailable() != 1) {
					return VIEW_ERROR;
				}
				shopCartService.insert(goodsId, type, userId);
			}
			return "redirect:/cart/index.html?command=shopCart";
		} else if ("shopCart".equals(command)) {
			//（临时购物车,用户购物车）
			//用户登录查询
			List<ShopCart> shopCartList = shopCartService.getListWithCourse(userId, 1);
			//总价格
			int totalMoney = 0;
			for (ShopCart sc : shopCartList) {
				Course course = sc.getCourse();
				if (course == null) {
					shopCartList.remove(sc);
					shopCartService.deleteById(sc.getId(), sc.getUserId());
				} else {
					totalMoney += course.getPrice();
				}
			}
			if ("ON".equals(CacheConstants.COUPON_IS_OPEN)) {
				//查询我的优惠券 查询可以使用 并且达到优惠券最低限额的优惠券
				CouponCodeQuery couponCodeQuery = new CouponCodeQuery();
				couponCodeQuery.setUserId(userId);
				couponCodeQuery.setLimitAmount(totalMoney);
				couponCodeQuery.setStatus(1);
				couponCodeQuery.setType(1);//查询课程优惠券（非会员优惠券）
				List<CouponCodeDTO> couponCodeList = couponCodeService.getDTOList(couponCodeQuery, null);
				mmap.put("couponCodeList", couponCodeList);
			}
			mmap.put("userAccount", userAccountService.getByUserId(userId));
			mmap.put("shopCartList", shopCartList);
			return getViewPath("shopcart/cart-course");
		} else {
			return VIEW_ERROR;
		}
	}

	/**
	 * 查询购物车（临时购物车,用户购物车）
	 */
	@RequestMapping(value = "/ajax/info.html")
	public String queryShopCartInfo(HttpServletRequest request, ModelMap mmap) {
		long userId = LoginUser.getUserId(request);
		int type = TKConvert.toInteger(request.getParameter("type"));
		List<ShopCart> shopCartList = shopCartService.getListWithCourse(userId, type);
		int totalMoney = 0;
		for (ShopCart shopcart : shopCartList) {
			/*如果订单里是套餐*/
			CourseDTO course = shopcart.getCourse();
			if (course == null) {
				shopCartList.remove(shopcart);
				shopCartService.deleteById(shopcart.getId(), shopcart.getUserId());
			} else {
				if ("PACKAGE".equals(course.getSellType())) {
					/*取套餐下的子课*/
					List<Integer> ids = new ArrayList<>();
					ids.add(course.getCourseId());
					List<CourseDTO> courseDTOList = courseService.getListByPackageIds(ids);
					/*给该订单的课程set 子课集合*/
					course.setCourseList(courseDTOList);
				}
				totalMoney += course.getPrice();
			}
		}
		mmap.put("shopcartList", shopCartList);
		mmap.put("totalMoney", totalMoney);
		return getViewPath("shopcart/cart-course-info");
	}

	/**
	 * 查询购物车列表(购物车图标 按钮使用)
	 */
	@RequestMapping(value = "/ajax/list.html")
	public String ajaxShopCartListRight(HttpServletRequest request, ModelMap mmap) {
		long userId = LoginUser.getUserId(request);
		int type = TKConvert.toInteger(request.getParameter("type"));
		List<ShopCart> shopCartList = shopCartService.getListWithCourse(userId, type);

		int totalMoney = 0;
		for (ShopCart sc : shopCartList) {
			Course course = sc.getCourse();
			if (course == null) {
				shopCartList.remove(sc);
				shopCartService.deleteById(sc.getId(), sc.getUserId());
			} else {
				totalMoney += course.getPrice();
			}
		}
		mmap.put("shopcartList", shopCartList);
		mmap.put("totalMoney", totalMoney);
		return getViewPath("shopcart/cart-course-ajax");
	}

	/**
	 * 删除购物车的一个Item ,Ajax 完成实时的 操作
	 */
	@RequestMapping(value = "/ajax/delete.json")
	@ResponseBody
	public AjaxResult deleteShopItem(Long id, HttpServletRequest request) {
		long userId = LoginUser.getUserId(request);
		if (userId < 1) {
			return AjaxResult.auth("亲，购物车需要登录后方可操作！");
		}
		shopCartService.deleteById(id, userId);
		return AjaxResult.success();
	}

	/**
	 * 根据type清空购物车
	 */
	@RequestMapping(value = "/ajax/clear.json")
	@ResponseBody
	public AjaxResult clearShopItem(HttpServletRequest request) {
		long userId = LoginUser.getUserId(request);
		if (userId < 1) {
			return AjaxResult.auth("亲，购物车需要登录后方可操作！");
		}
		int type = TKConvert.toInteger(request.getParameter("type"));
		shopCartService.deleteByUserId(userId, type);
		return AjaxResult.success();
	}

	/**
	 * 查询购物车（临时购物车,用户购物车）
	 */
	@RequestMapping(value = "/ajax/numbers.json")
	@ResponseBody
	public AjaxResult queryShopCartNums(HttpServletRequest request) {
		long userId = LoginUser.getUserId(request);
		if (userId < 1) {
			return AjaxResult.auth("亲，购物车需要登录后方可操作！");
		}
		int type = TKConvert.toInteger(request.getParameter("type"));
		List<ShopCart> shopCartList = shopCartService.getListByUserId(userId, type);
		int shopCartNum = 0;
		if (shopCartList != null) {
			shopCartNum = shopCartList.size();
		}
		return AjaxResult.success(shopCartNum);
	}

	/**
	 * ajax添加商品到购物车
	 */
	@RequestMapping(value = "/ajax/add.json")
	@ResponseBody
	public AjaxResult addShopCartAjax(HttpServletRequest request) {
		long userId = LoginUser.getUserId(request);
		if (userId < 1) {
			return AjaxResult.auth("亲，购物车需要登录后方可操作！");
		}
		int goodsId = TKConvert.toInteger(request.getParameter("goodsId"));// 商品id
		int type = TKConvert.toInteger(request.getParameter("type"));// 类型1课程2套餐
		if (goodsId > 0 && type > 0) {
			// 登录用户添加到数据库
			// 查询课程信息
			Course course = courseService.get(goodsId);
			if (course == null || course.getIsAvailable() != 1) {
				return AjaxResult.error("课程已下架");
			}
			shopCartService.insert(goodsId, type, userId);
			return AjaxResult.success();
		} else {
			return AjaxResult.error("参数错误！");
		}
	}
}
